package com.gyh.bootmybatis.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gyh.bootmybatis.entity.Book;
import com.gyh.bootmybatis.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    BookService bookService;

    @GetMapping("/page")
    public String getPage(@RequestParam(defaultValue = "1") Integer pageNum, Book book, Model model) {
        PageInfo<Book> pageInfo = bookService.getPage(pageNum, book);
        model.addAttribute("page", pageInfo);
        model.addAttribute("bookname", book.getName());
        model.addAttribute("author", book.getAuthor());
        return "bookPage";
    }


    @PostMapping("/del")
    public String del(Integer[] ids) {
        if (ids.length > 0) {
            bookService.del(ids);
        }
        return "redirect:/book/page";
    }

    @GetMapping("/add")
    public String goAdd() {
        return "add";
    }

    @PostMapping("/addBook")
    public String addBook(Book book) {
        Integer add = bookService.addBook(book);
        if (add > 0) {
            return "redirect:/book/page";
        } else {
            return "<script>console.log('添加失败！')</script>";
        }
    }

    @GetMapping("/getInfo")
    public String goUpdate(Model model, Integer id) {
        Book bookInfo = bookService.bookInfo(id);
        model.addAttribute("bookInfo",bookInfo);
        return "update";
    }

    @PostMapping("/updateBookInfo")
    public String updateBookById(Book book){
       Integer a=bookService.update(book);
       if (a>0){
           return "redirect:/book/page";
       }else {
           return null;
       }
    }
}
